package com.wzj.yygh.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.common.utils.JwtHelper;
import com.wzj.yygh.enums.AuthStatusEnum;
import com.wzj.yygh.model.user.Patient;
import com.wzj.yygh.model.user.UserInfo;
import com.wzj.yygh.user.mapper.UserInfoMapper;
import com.wzj.yygh.user.service.PatientService;
import com.wzj.yygh.user.service.UserInfoService;
import com.wzj.yygh.vo.user.LoginVo;
import com.wzj.yygh.vo.user.UserAuthVo;
import com.wzj.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public UserInfo selectUserInfoByOpenId(String openid) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getOpenid,openid);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //校验验证码是否正确
        String code = loginVo.getCode(); //验证码
        String phone = loginVo.getPhone();  //手机号
        //从redis中获取验证码进行比较
        String mobleCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(mobleCode)) {
            throw new YyghException("验证码错误",ResultCode.ERROR);
        }

        String openid = loginVo.getOpenid(); //微信的唯一标识
        UserInfo userInfo = null;
        if (StringUtils.isEmpty(openid)) {  //注册流程
            //根据手机号查找用户是否存在及是否被禁用
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getPhone,phone);
            userInfo = baseMapper.selectOne(queryWrapper);
            //如果存在直接登录否则注册用户
            if (userInfo != null && userInfo.getStatus() == 0) {
                throw new YyghException("用户已禁用", ResultCode.ERROR);
            }
            //登录
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setName(phone);
                userInfo.setNickName(phone);
                userInfo.setAuthStatus(AuthStatusEnum.NO_AUTH.getStatus());
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        } else { //绑定手机号流程
            //先判断系统是否存在当前手机号
            LambdaQueryWrapper<UserInfo> querywrapper = new LambdaQueryWrapper<>();
            querywrapper.eq(UserInfo::getPhone,phone);
            userInfo = baseMapper.selectOne(querywrapper);
            //校验是否被禁
            if (userInfo != null && userInfo.getStatus() != 0) {
                throw new YyghException("手机号已被注册",ResultCode.ERROR);
            }
            if (userInfo != null && userInfo.getStatus() == 0) {
                throw new YyghException("用户已被禁用",ResultCode.ERROR);
            }
            userInfo = this.selectUserInfoByOpenId(openid);
            userInfo.setPhone(phone); //绑定手机号
            baseMapper.updateById(userInfo);
        }
        // 生成令牌返回给前端
        String token = JwtHelper.createToken(userInfo.getId(),userInfo.getName());
//        String token = "";
        Map<String, Object> map = new HashMap<>();
        map.put("name",userInfo.getName());
        map.put("token",token);
        redisTemplate.delete(loginVo.getPhone());
        return map;
    }

    @Override
    public void saveUserAuthInfoByUserAuthVo(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setName(userAuthVo.getName());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        baseMapper.updateById(userInfo);
    }

    @Override
    public UserInfo getUserInfoById(Long userId) {
        return baseMapper.selectById(userId);
    }

    //分页条件查询
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> userInfoPage, UserInfoQueryVo userInfoQueryVo) {
        //userInfoQueryVo获取条件值
        String keyword = userInfoQueryVo.getKeyword();//用户名称
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        Page<UserInfo> pages = null;
        if (StringUtils.isEmpty(keyword) && StringUtils.isEmpty(createTimeBegin) && StringUtils.isEmpty(createTimeEnd)) {
            //调用mapper方法
            queryWrapper.orderByDesc(UserInfo::getCreateTime);
             pages = baseMapper.selectPage(userInfoPage, queryWrapper);
        }else {
            queryWrapper.and(i->i.like(UserInfo::getName,keyword))
                    .or().like(UserInfo::getPhone,keyword)
                    .ge(!StringUtils.isEmpty(createTimeBegin),UserInfo::getCreateTime,createTimeBegin)
                    .like(!StringUtils.isEmpty(createTimeEnd),UserInfo::getCreateTime,createTimeEnd);
            //调用mapper方法
            pages = baseMapper.selectPage(userInfoPage, queryWrapper);
        }
        //编号变成对应值封装
        pages.getRecords().forEach(this::packageUserInfo);
        return pages;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态0、1
        String statusString = userInfo.getStatus() == 0 ? "锁定": "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
    @Override
    public boolean lock(Long userId, Integer status) {
        if (status == 0 || status == 1) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setStatus(status);
            return this.updateById(userInfo);
        }
        return false;
    }

    //查询用户信息
    @Override
    public Map<String, Object> show(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userId查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    //认证审批 2通过 -1 不通过
    @Override
    public boolean approval(Long userId, Integer authStatus) {
        if (authStatus == AuthStatusEnum.AUTH_SUCCESS.getStatus() || authStatus == AuthStatusEnum.AUTH_FAIL.getStatus()) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setAuthStatus(authStatus);
            return this.updateById(userInfo);
        }
        return false;
    }
}
